package fc;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import fc.entity.OaEntity;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.upgradetool.wscheck.Util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ZH_YFSY_XQcopy implements Action{

	@Override
	public String execute(RequestInfo info) {
		String API_NAME="ZH_YFSY_XQ";

		BaseBean log = new BaseBean();

		log.writeLog("接口"+API_NAME+"开始调用-----------------------------------");

		OaEntity oe=new OaEntity();

		String requestid = info.getRequestid();
		String tablename = info.getRequestManager().getBillTableName();
		oe.setREQUESTID(requestid);

		String sql=
				"SELECT requestid,工程案号 GCAH,实验单号 SYDH,项目编号 XMBH,实验名称 SYMC from ( select requestid,syah 工程案号 ,sydh  实验单号,xmbh 项目编号,symc 实验名称  from "+tablename+"  o1  with(nolock)  where requestid="+requestid+")t ";
		RecordSet rs = new RecordSet();
		rs.executeSql(sql);
		if(rs.next()){
			oe.setGCAH(Util.null2String(rs.getString("GCAH")));
			oe.setSYDH(Util.null2String(rs.getString("SYDH")));
			oe.setXMBH(Util.null2String(rs.getString("XMBH")));
			oe.setSYMC(Util.null2String(rs.getString("SYMC")));


		}


		String sql1="select 料件编号 LJBH,数量 SL,单位 DW,物料需求时间 WLXQSJ,REM  from (select  o1.id,o1.ljbht100 料件编号,o1.gghsl 数量,o1.dw 单位,o2.wlxqsj 物料需求时间 ,o3.lastname  REM " +
				"from "+tablename+"_dt1 o1 with(nolock) ,"+tablename+" o2 with(nolock) ,hrmresource o3 with(nolock)  " +
				"where o1.mainid=o2.id and o1.sqr=o3.id  and o1.gglb='0' and o2.requestid="+requestid+")tt   order by id  ";

		RecordSet rs1 = new RecordSet();
		rs1.executeSql(sql1);
		while(rs1.next()){
			List<OaEntity> dts=oe.getDT1();
			OaEntity dt1=new OaEntity();

			dt1.setLJBH(Util.null2String(rs1.getString("LJBH")));
			dt1.setSL(Util.null2String(rs1.getString("SL")));
			dt1.setDW(Util.null2String(rs1.getString("DW")));
			dt1.setWLXQSJ(Util.null2String(rs1.getString("WLXQSJ")));
			dt1.setREM(Util.null2String(rs1.getString("REM")));


			dts.add(dt1);
			oe.setDT1(dts);
		}


		String testparam="";
		log.writeLog("接口"+API_NAME+"参数开始-----------------------------------"+oe.getREQUESTID());

		log.writeLog("main-----------------------------------");
		log.writeLog("工程案号 GCAH:"+oe.getGCAH()+",实验单号 SYDH:"+oe.getSYDH());
		testparam="";
		log.writeLog("dt1-----------------------------------");


		for(int i=0;i<oe.getDT1().size();i++){
			log.writeLog("料件编号 LJBH:"+oe.getDT1().get(i).getLJBH()+
					",数量 SL:"+oe.getDT1().get(i).getSL()+
					",单位 DW:"+oe.getDT1().get(i).getDW()+
					",物料需求时间 WLXQSJ:"+oe.getDT1().get(i).getWLXQSJ()
			);
			oe.setWLXQSJ(oe.getDT1().get(i).getWLXQSJ());
			if (!"".equals(testparam)){
				testparam=testparam+",";
			}
			testparam+=
					"{"+
							"\"seq_no\": \""+(i+1)+"\","+
							"\"part_no\": \" \","+
							"\"op_no\": \" \","+
							"\"op_seq\": \" \","+
							"\"bom_item_no\": \""+oe.getDT1().get(i).getLJBH()+"\","+
							"\"issue_item_no\": \""+oe.getDT1().get(i).getLJBH()+"\","+
							"\"product_feature_no\": \" \","+
							"\"mandatory_feature\": \"1\","+
							"\"recoil_material\": \"0\","+
							"\"allow_error_rate\": \"0\","+
							"\"adjust_issuance_qty\": \"0\","+
							"\"qty\": \""+oe.getDT1().get(i).getSL()+"\","+
							"\"unit_no\": \""+oe.getDT1().get(i).getDW()+"\","+
							"\"outsourcing_purchasing_qty\": \"0\","+
							"\"designation_warehouse_no\": \"\","+
							"\"designation_storage_spaces_no\": \"\","+
							"\"designation_lot_no\": \"\","+
							"\"designation_inventory_management_features\": \" \","+
							"\"remark\": \""+oe.getDT1().get(i).getREM()+"\""+
							"}";
		}


		DateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String  timestamp= format.format(new Date());


		DateFormat formataa = new SimpleDateFormat("yyyy-MM-dd");

		String createdate = formataa.format(new Date());

		String creater="MW20092103201";
		oe.setLJBH("DPJ-MWI-2024080001-01");
		oe.setSL("1");
		oe.setDW("PCS");
		oe.setREM(oe.getGCAH()+"("+oe.getSYMC()+")");

		String json_param=
				"{"+
						"\"key\": \"dccb6a7b66b7e1d13dbe68ed70084b7c\","+
						"\"type\": \"sync\","+
						"\"host\": {"+
						"\"prod\": \"OAPI\","+
						"\"ip\": \"192.168.0.30\","+
						"\"lang\": \"zh_CN\","+
						"\"acct\": \"tiptop\","+
						"\"timestamp\": \""+timestamp+"\""+//--时间戳要改
						"},"+
						"\"service\": {"+
						"\"prod\": \"T100\","+
						"\"name\": \"t100.oapi.wo.data.crt\","+
						"\"ip\": \"192.168.0.30\","+
						"\"id\": \"topprd\""+
						"},"+
						"\"datakey\": {"+
						"\"EntId\": \"2\","+
						"\"CompanyId\": \"ZH00\""+
						"},"+
						"\"payload\": {"+
						"\"std_data\": {"+
						"\"parameter\": {"+
						"\"enterprise_no\": \"2\","+
						"\"site_no\": \"ZH00\","+
						"\"is_digiwin_product\": \"Y\","+
						"\"wo_info\": ["+
						"{"+
						"\"source_no\": \"来源单号-orig-bill-test\","+
						"\"doc_slip\": \"YFNPJ\","+
						"\"doc_date\": \""+createdate+"\","+
						"\"production_control_no\": \""+creater+"\","+
						"\"wo_type\": \"4\","+
						"\"outsourcing_type\": \"1\","+
						"\"issue_rule\": \"1\","+
						"\"production_item_no\": \""+oe.getLJBH()+"\","+
						"\"production_item_feature\": \" \","+
						"\"production_qty\": \""+oe.getSL()+"\","+
						"\"production_unit_no\": \""+oe.getDW()+"\","+
						"\"process_no\": \"\","+
						"\"wo_source_type\": \"0\","+
						"\"wo_source\": \"\","+
						"\"wo_source_seq\": \"\","+
						"\"wo_source_term_seq\": \"\","+
						"\"plan_date_s\": \""+oe.getWLXQSJ()+"\","+
						"\"department_supplier_no\": \"\","+
						"\"cost_center_no\": \"10000159\","+
						"\"bom_version\": \"\","+
						"\"pbi_no\": \"\","+
						"\"urgency_rate\": \"\","+
						"\"priority_seq\": \"\","+
						"\"project_no\": \""+oe.getXMBH()+"\","+
						"\"workstation_id\": \"\","+
						"\"shift_no\": \"\","+
						"\"plan_stock_in_warehouse_no\": \"\","+
						"\"plan_stock_in_location_no\": \"\","+
						"\"plan_stock_in_lot_no\": \"\","+
						"\"plan_stock_in_inventory_management_features\": \" \","+
						"\"create_employee_no\": \""+creater+"\","+
						"\"create_date\": \""+createdate+"\","+
						"\"remark\": \""+oe.getREM()+"\","+
						"\"doc_approve_set\": \"N\","+
						"\"prepare_material_detail\": ["+

						testparam+

						"],"+
						"\"production_item_no_list\": ["+
						"{"+
						"\"production_type\": \"1\","+
						"\"item_no\": \""+oe.getLJBH()+"\","+
						"\"product_feature\": \" \","+
						"\"plan_output_qty\": \""+oe.getSL()+"\""+
						"}"+
						"]"+
						"}"+
						"]"+
						"}"+
						"}"+
						"}"+
						"}";

		log.writeLog("接口"+API_NAME+"json_param:"+json_param);

		String result="ERROR";
		if(!"".equals(testparam)){
			String data = HttpRequest.post(FcHttpCon.ZH_YFSY_XQ).body(json_param).execute().body();
			log.writeLog("接口"+API_NAME+"返回-----------------------------------"+data);
			try {
				Object succesResponse = JSON.parse(data);
				Map map = (Map)succesResponse;
				Map map1 = (Map)map.get("payload");
				Map map2 = (Map)map1.get("std_data");
				Map map3 = (Map)map2.get("execution");
				if("0".equals(map3.get("code"))){
					result="SUCCESS";
				}
			} catch (Exception e) {}
		}else{
			result="NOTNEED";
		}

		if("SUCCESS".equals(result)){
			//记录数据
			RecordSet rsg = new RecordSet();
			String sqlg="INSERT INTO FC_API_DIAOYONG_JILU VALUES('"+API_NAME+"',"+requestid+",GETDATE())";
			rsg.executeSql(sqlg);
		}else if("NOTNEED".equals(result)){
		}else{
			info.getRequestManager().setMessagecontent("接口调用失败无法提交！请联系管理员具体查看");
			return FAILURE_AND_CONTINUE;
		}
		return SUCCESS;


	}

	public static String sendPost(String url, String param) {

		PrintWriter out = null;
		BufferedReader in = null;
		StringBuilder result = new StringBuilder();
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Accept-Charset", "UTF-8");
			conn.setRequestProperty("contentType", "UTF-8");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
//			System.out.println("发送 POST 请求出现异常！" + e);
			result = new StringBuilder("{\"msg\":\"SB\",\"errCode\":\"1001\"}");
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result.toString();
	}





} 